package com.bigpang.framework.JdkDynamicProxy;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;

/**
 * @Author YongQiang
 * @Date 2021/7/13 14:10
 * @Version 1.0
 */
public class MyProxyTest {
    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        IHelloImpl hello = new IHelloImpl();
        IHello proxy = (IHello) MyProxyTest.getProxy(hello);
        proxy.sayHello();
    }

    public static Object getProxy(Object object) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Object o = null;
        /**
         *
         * 一步到位
         *
         * loader 加载代理对象的类加载器
         * interfaces 代理对象实现的接口，与目标对象实现同样的接口
         * h 处理代理对象逻辑的处理器，即自定义的 InvocationHandler 实现类。
         */
        o = Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),
                new MyInvocationHandler(object));

        /**
         * 创建代理类并生成相应的代理对象
         */
        Class<?> proxyClass = Proxy.getProxyClass(object.getClass().getClassLoader(), object.getClass().getInterfaces());

        InvocationHandler invocationHandler = new MyInvocationHandler(object);
        Constructor<?> constructor = proxyClass.getConstructor(new Class[]{InvocationHandler.class});
        o = constructor.newInstance(invocationHandler);
        return o;
    }
}
